package com.cyw.common.domain.common;

import com.cyw.common.utils.BaseUtils;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;

import static com.cyw.common.utils.StreamUtils.propList;


/**
 * List包装类
 *
 * @author cyw
 * @date 2021/3/1 13:55
 **/
@Data
@Accessors(chain = true)
public class ListWrapper<T> implements Serializable {

    private static final long serialVersionUID = -8430694678658455125L;

    /**
     * 列表
     */
    private Collection<T> list;

    private ListWrapper(Collection<T> list) {
        this.list = list;
    }

    public static <E> ListWrapper<E> empty() {
        return new ListWrapper<E>(new ArrayList<E>());
    }

    public void add(T element) {
        this.list.add(element);
    }

    public Boolean isEmpty() {
        return BaseUtils.isEmpty(this.list);
    }

    public static <Element, Prop> ListWrapper<Prop> convert(Collection<Element> list, Function<Element, Prop> propExtractor) {
        List<Prop> props = propList(list, propExtractor, false);
        return ListWrapper.toWrapper(props);
    }

    /**
     * 获取集合指定类型<Prop>的 ListWrapper 「不会过滤非空元素」
     */
    public static <Element, Prop> ListWrapper<Prop> convert(ListWrapper<Element> list, Function<Element, Prop> propExtractor) {
        List<Prop> props = propList(list.getList(), propExtractor, false);
        return ListWrapper.toWrapper(props);
    }

    public static <T> ListWrapper<T> toWrapper(Collection<T> list) {
        return new ListWrapper<T>(list);
    }

}
